<template>
  <div class="all-clue">
    <div class="filter">
      <span style="margin-right: 30px">快捷筛选:</span>
      <el-button
        :class="{ 'active-button': activeButton === 'button0' }"
        @click="toggleButton('button0', 4)"
      >
        全部
      </el-button>
      <el-button
        :class="{ 'active-button': activeButton === 'button1' }"
        @click="toggleButton('button1', 3)"
      >
        今日新增
      </el-button>

      <el-button
        :class="{ 'active-button': activeButton === 'button2' }"
        @click="toggleButton('button2', 1)"
      >
        本周新增
      </el-button>

      <el-button
        :class="{ 'active-button': activeButton === 'button3' }"
        @click="toggleButton('button3', 2)"
      >
        本月新增
      </el-button>
    </div>
    <div class="current-students-search">
      <el-form :model="form" ref="ruleFormRef" label-width="auto">
        <el-row :gutter="0" style="margin-bottom: 10px">
          <el-col :span="6">
            <el-form-item label="搜索学员:">
              <el-input
                v-model="searchName"
                style="width: 80%"
                placeholder="请输入学员姓名/手机号"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="学员来源:">
              <el-select
                v-model="searchJoinWay"
                placeholder="请选择学员来源"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in joinWayList.value"
                  :key="item.dictCode"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年级:">
              <el-select
                v-model="gradeName"
                placeholder="请选择年级"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in gradeList.value"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" icon="Search" @click="toSearch"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="toClear(ruleFormRef)"
              >重置</el-button
            >
          </el-col>
        </el-row>
        <el-row :gutter="0" style="margin-bottom: 10px">
          <el-col :span="6">
            <el-form-item label="搜索学校:">
              <el-input
                v-model="attendSchool"
                style="width: 80%"
                placeholder="请输入学校名称"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="学员创建人:">
              <el-select
                v-model="creatorName"
                placeholder="请选择学员创建人"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in peopleList.value"
                  :key="item.id"
                  :label="item.nickName"
                  :value="item.id"
                >
                  {{ item.nickName }}{{ !item.isJob ? "(已离职)" : "" }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="padding-right: 4%">
            <el-form-item label="创建时间:">
              <el-date-picker
                v-model="cTime"
                type="daterange"
                unlink-panels
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 80%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="0" style="margin-bottom: 10px">
         
          <el-col :span="8">
            <span class="search-label"> 学员年龄:</span>
            <el-time-picker
              v-model="value1"
              is-range
              range-separator="To"
              start-placeholder="Start time"
              end-placeholder="End time"
              style="width: 80%"
              @change="toSearch"
            />
          </el-col>
        </el-row> -->
      </el-form>
    </div>
    <div class="manage-students">
      <el-button
        type="primary"
        @click="openEditStudents"
        v-hasPermi="['sales:clue:add']"
        >添加线索</el-button
      >
      <el-button
        plain
        @click="openShareDialog('跟进人')"
        v-hasPermi="['sales:clue:distribute']"
        >分配跟进人</el-button
      >
      <el-button
        v-show="selectedClue === 0"
        type="plain"
        plain
        icon="Upload"
        @click="handleImport"
        >导入学员</el-button
      >
      <!-- <el-button
        v-show="selectedClue === 0"
        type="plain"
        plain
        icon="Download"
        @click="handleExport"
        >导出学员</el-button
      > -->
    </div> 
    <!-- 表格 -->
    <div class="students-table">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="学员姓名" fixed="left" width="180">
          <template #default="scope">
            <router-link
              :to="'/registrar/studentsDetails/detail/' + scope.row.id"
              class="link-type"
            >
              <div style="display: flex; align-items: center">
                <span
                  style="margin-right: 10px; color: #67c23a; cursor: pointer"
                  >{{ scope.row.name }}</span
                >
                <el-icon v-if="scope.row.gender == '1'" style="color: #fb6465"
                  ><Female
                /></el-icon>
                <el-icon
                  v-else-if="scope.row.gender == '0'"
                  style="color: #4791ed"
                  ><Male
                /></el-icon>
              </div>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column
          property="mobile"
          label="手机号"
          fixed="left"
          show-overflow-tooltip
          :formatter="formatName"
          width="180"
        />
        <el-table-column
          property="joinName"
          label="学员来源"
          show-overflow-tooltip
          :formatter="formatName"
          width="180"
        />
        <el-table-column
          label="年龄"
          show-overflow-tooltip
          :formatter="formatName"
          width="150"
        >
          <template #default="scope">
            {{ scope.row.ageName ? `${scope.row.ageName}岁` : "-" }}
          </template>
        </el-table-column>
        <el-table-column
          property="gradeName"
          label="年级"
          show-overflow-tooltip
          :formatter="formatName"
          width="150"
        />
        <el-table-column
          property="birthday"
          label="出生日期"
          show-overflow-tooltip
          :formatter="formatName"
          width="150"
        />
        <el-table-column
          property="attendSchool"
          label="学校"
          show-overflow-tooltip
          :formatter="formatName"
          width="150"
        />
        <el-table-column
          property="creatName"
          label="学员创建人"
          show-overflow-tooltip
          :formatter="formatName"
          width="150"
        />
        <el-table-column
          property="addTime"
          label="创建时间"
          show-overflow-tooltip
          :formatter="formatName"
          width="180"
        />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              v-hasPermi="['sales:clue:follow']"
              link
              type="primary"
              @click="toClue(scope.row)"
              >跟进</el-button
            >
            <router-link
              :to="'/registrar/studentsSignUp/index/' + scope.row.id"
              class="link-type"
            >
              <el-button link type="primary">报名</el-button>
            </router-link>

            <el-button
              link
              type="primary"
              @click="handleDelete(scope.row)"
              v-hasPermi="['sales:clue:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="total"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        @pagination="toGetCurrentStudentsList"
      />
      <div style="height: 10px"></div>
    </div>
    <ShareDialog
      :isShowShare="isShowShare"
      :shareType="shareType"
      :students="multipleSelection"
      @update:isShowShare="updateShowShare"
      @update:tableList="toGetCurrentStudentsList"
    />
    <!-- 新建线索 -->
    <EditStudents
      type="新建"
      :isShowEdit="isShowEdit"
      @update:isShowEdit="updateShowEdit"
      @update:students="updateStudents"
    />
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?stage=1'"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileError"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="cancelImport">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Pagination from "@/components/Pagination/index.vue";
import ShareDialog from "../../../registrar/student/components/shareDialog/index.vue";
import EditStudents from "../../../registrar/student/components/editStudents/index.vue";

import { ref, reactive, provide } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import useRegistrarStore from "@/store/modules/registrar";
import {
  getStudentsList,
  getStaffList,
  getJoinWayList,
  getFollowPeopleList,
  getClassList,
  getGradeList,
  deleteClue,
  cluefollow,
  getAssignStudents,
  toExport,
  toExportTemplate,
} from "@/api/studentManagement/index.js";
import {
  getToken,
  getLoginDeptParentAuth,
  getLoginDeptAuth,
} from "@/utils/auth";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();

const props = defineProps({
  selectedClue: {
    type: Number,
    default: 0,
  },
});
const { proxy } = getCurrentInstance();
const loading = ref(true);
//创建store
const registrarStore = useRegistrarStore();
//筛选
const searchName = ref(""); //学员搜索
const cTime = ref("");
const attendSchool = ref("");
//获取学员来源下拉列表
const searchJoinWay = ref(""); //学员来源
const joinWayList = reactive([]); //学员来源列表
provide("joinWayList", joinWayList); //传值给后代
const toGetJoinWayList = async () => {
  try {
    const res = await getJoinWayList();
    if (res.code == 200) {
      joinWayList.value = res.data;
      registrarStore.setJoinWayList(joinWayList.value);
    }
  } catch (error) {
    console.error("获取学员来源下拉列表失败:", error);
  }
};
onMounted(toGetJoinWayList);
//获取工作人员下拉列表
const people = ref(""); //跟进人
const studyPeople = ref(""); //学管师
const creatorName = ref(""); //学员创建人
// const classPeople = ref('') //班级老师
const peopleList = reactive([]); //工作人员列表
provide("peopleList", peopleList); //传值给后代
const toGetPeopleList = async () => {
  try {
    const res = await getFollowPeopleList({ pageNum: 1, pageSize: 9999 });
    if (res.code == 200) {
      peopleList.value = res.rows;
    }
  } catch (error) {
    console.error("获取工作人员下拉列表失败:", error);
  }
};
onMounted(toGetPeopleList);
//获取所在班级下拉列表
const classN = ref("");
const classList = reactive([]); //所在班级列表
const toGetClassList = async () => {
  try {
    const res = await getClassList({});
    if (res.code == 200) {
      classList.value = res.data;
      registrarStore.setClassList(classList.value);
    }
  } catch (error) {
    console.error("获取所在班级下拉列表失败:", error);
  }
};
onMounted(toGetClassList);
//获取年级下拉列表
const gradeName = ref("");
const gradeList = reactive([]); //所在班级列表
const toGetGradeList = async () => {
  try {
    const res = await getGradeList({});
    if (res.code == 200) {
      gradeList.value = res.data;
      registrarStore.setGradeList(gradeList.value);
    }
  } catch (error) {
    console.error("获取年级下拉列表失败:", error);
  }
};
onMounted(toGetGradeList);

//筛选学员列表
function toSearch() {
  toGetCurrentStudentsList();
}

//控制折叠
const isCollapse = ref(true);
function setCollapse() {
  isCollapse.value = !isCollapse.value;
}
//控制分配弹窗
const isShowShare = ref(false);
const shareType = ref(1);
const openShareDialog = (type) => {
  if (multipleSelection.value.length) {
    shareType.value = type;
    isShowShare.value = true;
  } else {
    ElMessage({
      message: "请选择要分配的学员",
      type: "warning",
    });
  }
};
const updateShowShare = (value) => {
  isShowShare.value = value;
};

//表格多选操作
const multipleTableRef = ref();
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  console.log("444", multipleSelection.value);
};
//分页器
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
//处理日期格式
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以加1
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};
//获取表格数据
const tableData = ref([]);
const clueType = ref(4);
const toGetCurrentStudentsList = async () => {
  loading.value = true;
  const params = {
    stage: 1,
    type: clueType.value,
    mine: props.selectedClue,
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    wxParam: searchName.value,
    attendSchool: attendSchool.value,
    joinWay: searchJoinWay.value,
    gradeId: gradeName.value,
    creator: creatorName.value,
    startTime: cTime.value ? formatDate(cTime.value[0]) : "",
    endTime: cTime.value ? formatDate(cTime.value[1]) : "",
  };
  try {
    const res = await getStudentsList(params);
    if (res.code == 200) {
      total.value = res.total;
      tableData.value = res.rows;
      loading.value = false;
    }
  } catch (error) {
    console.error("获取学生列表失败:", error);
  }
};
onMounted(toGetCurrentStudentsList);
//表格没有数据显示'-'
const formatName = (row, column, cellValue) => {
  return cellValue === "" || cellValue === null ? "-" : cellValue;
};
//将学员跟进人转为账号登录人
const toClue = (row) => {
  ElMessageBox.confirm(
    "系统将添加你作为此条线索的跟进人。后续的线索跟进将由你负责。",
    "确定作为跟进人？",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        const res = await getAssignStudents({
          ids: [row.id],
          counselorId: userStore.id,
        });
        if (res.code == 200) {
          toGetCurrentStudentsList();
          ElMessage({
            type: "success",
            message: "跟进成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "跟进失败",
          });
        }
      } catch (error) {
        console.error("跟进失败:", error);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消跟进",
      });
    });
};
//删除学员
const handleDelete = (row) => {
  ElMessageBox.confirm("是否将学员放入回收站", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await deleteClue({
          id: row.id,
          type: 1,
        });
        if (res.code == 200) {
          toGetCurrentStudentsList();
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "删除失败",
          });
        }
      } catch (error) {
        console.error("删除失败:", error);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
//清空搜索内容
const toClear = () => {
  searchName.value = "";
  searchJoinWay.value = "";
  studyPeople.value = "";
  gradeName.value = "";
  cTime.value = "";
  attendSchool.value = "";
  creatorName.value = "";
  pageNum.value = 1;
  toGetCurrentStudentsList();
};

//操控新建dialog
const isShowEdit = ref(false);
const openEditStudents = () => {
  isShowEdit.value = true;
};
//监听新建组件数据
const updateShowEdit = (value) => {
  isShowEdit.value = value;
};
const updateStudents = () => {
  toGetCurrentStudentsList();
};
//快捷筛选操作
const activeButton = ref("button0");
function toggleButton(value, type) {
  activeButton.value = activeButton.value === value ? null : value;
  clueType.value = type;
  toGetCurrentStudentsList();
}

//导入导出部分---------------------------------------------------------
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "导入学员",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  // updateSupport: 0,
  // 设置上传的请求头部
  headers: {
    Authorization: "Bearer " + getToken(),
    LoginDeptParentAuth: getLoginDeptParentAuth(),
    LoginDeptAuth: getLoginDeptAuth(),
  },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/student/import",
});
//导入
function handleImport() {
  upload.open = true;
  //importClassListAPI().then((res) => {});
}
//确定导入
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
//取消导入
const cancelImport = () => {
  upload.open = false;
  proxy.$refs["uploadRef"].clearFiles();
};
const handleFileSuccess = (res) => {
  upload.open = false;
  proxy.$refs["uploadRef"].clearFiles();
  pageNum.value = 1;
  toGetCurrentStudentsList();
  if (res.code == 200) {
    ElMessage({
      message: res.msg,
      type: "success",
    });
  } else {
    ElMessage({
      message: res.msg,
      type: "error",
    });
  }
};
const handleFileError = (err) => {
  console.log("上传失败:", err);
  ElMessage({
    message: "上传失败",
    type: "error",
  });
};

//导出
function handleExport() {
  toExport({ stage: 1, type: clueType.value, mine: 0 }).then((res) => {
    let blob = new Blob([res], {
      type: "application/vnd.ms-excel;charset=utf-8",
    });
    //var contentDisposition = decodeURI(res.headers["content-disposition"]);
    const url = window.URL.createObjectURL(blob),
      link = document.createElement("a"); // 创建a标签
    link.href = url;
    link.download = "线索学员列表";
    link.click();
    URL.revokeObjectURL(url); // 释放内存
    proxy.$modal.msgSuccess("导出成功");
  });
}

/** 下载模板操作 */
function importTemplate() {
  toExportTemplate({ stage: 1 })
    .then((res) => {
      let blob = new Blob([res], {
        type: "application/vnd.ms-excel;charset=utf-8",
      });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "导入模板.xls";
      document.body.appendChild(a); // 添加到 DOM
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    })
    .catch((error) => {
      console.error("下载模板失败:", error);
    });
}
</script>

<style lang="scss" scoped>
.all-clue {
  .filter {
    margin: 20px 0;

    color: #666;
    .active-button {
      background-color: #409eff; /* 自定义高亮颜色 */
      color: white; /* 字体颜色 */
      border-color: #409eff; /* 边框颜色 */
    }
  }
  // position: relative;
  .current-students-search {
    position: relative;
    .search-label {
      display: inline-block;
      width: 18%;
      text-align: right;
      margin-right: 8px;
      font-size: 14px;
    }
    .current-students-search-main {
      width: 90%;

      .search-collapse {
        // height: 500px;
        // background-color: red;
      }
    }
  }
  .manage-students {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    height: 40px;
    // background-color: red;
  }
}
</style>
